<?php

namespace app\admin\controller\user;

use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\model\Hospital;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $noNeedRight = 'selectpage2,selectpage3';
    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    protected $Ids = null;
    protected $user = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->Ids=$this->auth->getGroupIds();
        $this->user=$this->auth->getUserInfo();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1="1=1";
            $list = $this->model
                    ->with('group')
                    ->where($where)
                    ->where(["identity"=>0])
                    ->order($sort, $order)
                    ->paginate($limit);

            if($this->Ids[0]==2) {
                $admin = Admin::get($this->user["id"]);
                if ($admin) {
                    $hospital = Hospital::field("user_ids")->where(["status" => 1])->where('FIND_IN_SET("' . $this->user["id"] . '", admin_ids)')->find();
                    if ($hospital) {
                        $list = $this->model
                            ->with('group')
                            ->where($where)
                            ->whereIn("user.id", $hospital["user_ids"])
                            ->where(["identity" => 0])
                            ->order($sort, $order)
                            ->paginate($limit);
                    }
                }
            }
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }
    /**
     * 新增
     * */
    public function selectpage2()
    {
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        if($this->request->request("searchKey")){
            $where="  id in (".$this->request->param("ids").")" ;
        }else{
            if($this->request->param("ids")){
                $where=" id NOT IN (SELECT 
SUBSTRING_INDEX( SUBSTRING_INDEX( a.user_ids, ',', b.help_topic_id + 1 ), ',',- 1 ) id
FROM yl_hospital a
JOIN help_topic b ON b.help_topic_id < ( LENGTH( a.user_ids ) - LENGTH( REPLACE ( a.user_ids, ',',''))+1) 
) or id in (".$this->request->param("ids").")" ;
            }else{
                $where=" id NOT IN (SELECT 
SUBSTRING_INDEX( SUBSTRING_INDEX( a.user_ids, ',', b.help_topic_id + 1 ), ',',- 1 ) id
FROM yl_hospital a
JOIN help_topic b ON b.help_topic_id < ( LENGTH( a.user_ids ) - LENGTH( REPLACE ( a.user_ids, ',',''))+1) 
) " ;
            }
        }
        $datalist = $this->model
            ->whereLike("nickname","%".$this->request->param("nickname")."%")
            ->where($where)
            ->where(["identity"=>0])
            ->page($page, $pagesize)
            ->select();
        $total = $this->model
            ->whereLike("nickname","%".$this->request->param("nickname")."%")
            ->where($where)
            ->page($page, $pagesize)->count();
        return json(['list' => $datalist, 'total' => $total]);
    }
    public function selectpage3()
    {
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        if($this->request->request("searchKey")){
            $where="  id in (".$this->request->param("ids").")" ;
        }else{
            $where=" identity ='".$this->request->param("type")."'" ;
        }
        $datalist = $this->model
            ->whereLike("nickname","%".$this->request->param("nickname")."%")
            ->where($where)
            ->page($page, $pagesize)
            ->select();
        $total = $this->model
            ->whereLike("nickname","%".$this->request->param("nickname")."%")
            ->where($where)
            ->count();
        return json(['list' => $datalist, 'total' => $total]);
    }
}
